//
// Created by bill3000 on 2/14/21.
// To start UI interactive thread, all you need to do is
// call UIInteractive::start_ui_interactive_thread();
// all is done.
//

#include "ui.hpp"
#include "../fsm/macros.hpp"

extern bool running;

pthread_t UIInteractive::ui_interactive_thread_id;
UIInteractive *UIInteractive::ui;

void UIInteractive::start_ui_interactive_thread(){
    int ret;
    ui = new UIInteractive();

    ret = pthread_create(&ui_interactive_thread_id, nullptr, ui_interactive_thread, (void *)ui);
    if(ret!=0) {
        LOG(ERROR, "Failed to create UI interactive thread !");
        exit(1);
    }
}

void UIInteractive::wait_ui_interactive_thread() {
    pthread_join(ui_interactive_thread_id, nullptr);
}

void UIInteractive::stop_ui_interactive_thread() {
    pthread_cancel(ui_interactive_thread_id);
}

void UIInteractive::dispose() {
    Queue::dispose();
    delete ui;
}

void* UIInteractive::ui_interactive_thread(void *data) {
    auto *uia = (UIInteractive *)data;
    uia->runner();
    pthread_exit(nullptr);
}

UIInteractive::UIInteractive() {
    mq = Queue::get_instance();
    ui = nullptr;
}

void UIInteractive::runner() {
    Message message;
    int ret;

    LOG(INFO, "Start UI interactive thread successfully !");
    while(running) {
        ret = mq->receive_message(M01, &message, MESSAGE_DIRECTION_FROM_WEB);

        if (ret == -1) continue;
        std::cout << "receive_message in M01!Forwarding to M02......" <<std::endl;

        //Change mtype's value to 300 and send message to M02
        message.mtype = MESSAGE_DIRECTION_UI_THREAD_TO_SORTING_THREAD;
        mq->send_message(M02, &message);
    }
}

